#include "StdAfx.h"
#include "Gate.h"
#include <iostream>

Gate::Gate( const char* szID )
	: Node( szID )
{
}

Gate::Gate()
{
	output = new Output();
	linkedInputs = 0;
}


Gate::~Gate(void)
{
	delete output;
	int cap = inputs.size();
	for(int i = 0; i < cap; i++)
	{
		delete inputs[i];
	}
	inputs.clear();
}


int Gate::GetLinkedInputs()
{
	return linkedInputs;
}

Input* Gate::GetInput(int i)
{
	return inputs[i];
}

const vector<Input*> Gate::GetInputs()
{
	return inputs;
}

Output* Gate::GetOutput()
{
	return output;
}

void Gate::AddInput(Input* input)
{
	inputs.push_back(input);
}

void Gate::SetOutput(Output* output)
{
	this->output = output;
}


Input* Gate::GetInputForLink()
{
	if(linkedInputs + 1 <= this->GetInputs().size())
	{
		return this->GetInput(linkedInputs++);
	}
	else
	{
		return NULL;
	}
}
void Gate::LinkOutputWith(Input* input)
{
	this->GetOutput()->AttachInput(input);
}

void Gate::LinkInputsWithGate()
{
	int length = this->GetInputs().size();
	for(int i = 0; i < length; i++)
	{
		this->GetInput(i)->registerObserver(this);
	}
}

bool Gate::AllInputsWereSet()
{
	//cout << "inputCheck"<< endl;
	//int nrOfInputs = inputs.size();
	for(int i = 0; i < inputs.size(); i++)
	{
		if(!inputs[i]->IsSet())
		{
			return false;
		}
	}
	return true;
}

void Gate::notify()
{
	if(AllInputsWereSet())
	{
		this->Calculation();
	}
}